{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "copyright"
      },
      "outputs": [],
      "source": [
        "# Copyright 2020 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "title"
      },
      "source": [
        "# Vertex client library: AutoML tabular classification model for export to cloud\n",
        "\n",
        "<table align=\"left\">\n",
        "  <td>\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/community/gapic/automl/showcase_automl_tabular_classification_export_cloud.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/community/gapic/automl/showcase_automl_tabular_classification_export_cloud.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
        "      View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "</table>\n",
        "<br/><br/><br/>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "overview:automl,export_cloud"
      },
      "source": [
        "## Overview\n",
        "\n",
        "\n",
        "This tutorial demonstrates how to use the Vertex client library for Python to create tabular classification models to export as a cloud model using Google Cloud's AutoML."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dataset:iris,lcn"
      },
      "source": [
        "### Dataset\n",
        "\n",
        "The dataset used for this tutorial is the [Iris dataset](https://www.tensorflow.org/datasets/catalog/iris) from [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/overview). This dataset does not require any feature engineering. The version of the dataset you will use in this tutorial is stored in a public Cloud Storage bucket. The trained model predicts the type of Iris flower species from a class of three species: setosa, virginica, or versicolor."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "objective:automl,training,export_cloud"
      },
      "source": [
        "### Objective\n",
        "\n",
        "In this tutorial, you create a AutoML tabular classification model from a Python script using the Vertex client library, and then export the model in a TensorFlow SavedModel format. You can alternatively create models with AutoML using the the `gcloud` command-line tool or online using the Google Cloud Console.\n",
        "\n",
        "The steps performed include:\n",
        "\n",
        "- Create a Vertex `Dataset` resource.\n",
        "- Train the model.\n",
        "- Export the model from the `Model` resource to Cloud Storage.\n",
        "- Download the model locally.\n",
        "- Make a local prediction."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "costs"
      },
      "source": [
        "### Costs\n",
        "\n",
        "This tutorial uses billable components of Google Cloud (GCP):\n",
        "\n",
        "* Vertex AI\n",
        "* Cloud Storage\n",
        "\n",
        "Learn about [Vertex AI\n",
        "pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
        "pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
        "Calculator](https://cloud.google.com/products/calculator/)\n",
        "to generate a cost estimate based on your projected usage."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_aip"
      },
      "source": [
        "## Installation\n",
        "\n",
        "Install the latest version of Vertex client library."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "install_aip"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "# Google Cloud Notebook\n",
        "if os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
        "    USER_FLAG = \"--user\"\n",
        "else:\n",
        "    USER_FLAG = \"\"\n",
        "\n",
        "! pip3 install -U google-cloud-aiplatform $USER_FLAG"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_storage"
      },
      "source": [
        "Install the latest GA version of *google-cloud-storage* library as well."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "install_storage"
      },
      "outputs": [],
      "source": [
        "! pip3 install -U google-cloud-storage $USER_FLAG"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "restart"
      },
      "source": [
        "### Restart the kernel\n",
        "\n",
        "Once you've installed the Vertex client library and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "restart"
      },
      "outputs": [],
      "source": [
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Automatically restart kernel after installs\n",
        "    import IPython\n",
        "\n",
        "    app = IPython.Application.instance()\n",
        "    app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "before_you_begin"
      },
      "source": [
        "## Before you begin\n",
        "\n",
        "### GPU runtime\n",
        "\n",
        "*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n",
        "\n",
        "### Set up your Google Cloud project\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
        "\n",
        "2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
        "\n",
        "3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n",
        "\n",
        "4. [The Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebook.\n",
        "\n",
        "5. Enter your project ID in the cell below. Then run the  cell to make sure the\n",
        "Cloud SDK uses the right project for all the commands in this notebook.\n",
        "\n",
        "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "set_project_id"
      },
      "outputs": [],
      "source": [
        "PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_project_id"
      },
      "outputs": [],
      "source": [
        "if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
        "    # Get your GCP project id from gcloud\n",
        "    shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
        "    PROJECT_ID = shell_output[0]\n",
        "    print(\"Project ID:\", PROJECT_ID)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "set_gcloud_project_id"
      },
      "outputs": [],
      "source": [
        "! gcloud config set project $PROJECT_ID"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "region"
      },
      "source": [
        "#### Region\n",
        "\n",
        "You can also change the `REGION` variable, which is used for operations\n",
        "throughout the rest of this notebook.  Below are regions supported for Vertex. We recommend that you choose the region closest to you.\n",
        "\n",
        "- Americas: `us-central1`\n",
        "- Europe: `europe-west4`\n",
        "- Asia Pacific: `asia-east1`\n",
        "\n",
        "You may not use a multi-regional bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see the [Vertex locations documentation](https://cloud.google.com/vertex-ai/docs/general/locations)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "region"
      },
      "outputs": [],
      "source": [
        "REGION = \"us-central1\"  # @param {type: \"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "timestamp"
      },
      "source": [
        "#### Timestamp\n",
        "\n",
        "If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "timestamp"
      },
      "outputs": [],
      "source": [
        "from datetime import datetime\n",
        "\n",
        "TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gcp_authenticate"
      },
      "source": [
        "### Authenticate your Google Cloud account\n",
        "\n",
        "**If you are using Google Cloud Notebook**, your environment is already authenticated. Skip this step.\n",
        "\n",
        "**If you are using Colab**, run the cell below and follow the instructions when prompted to authenticate your account via oAuth.\n",
        "\n",
        "**Otherwise**, follow these steps:\n",
        "\n",
        "In the Cloud Console, go to the [Create service account key](https://console.cloud.google.com/apis/credentials/serviceaccountkey) page.\n",
        "\n",
        "**Click Create service account**.\n",
        "\n",
        "In the **Service account name** field, enter a name, and click **Create**.\n",
        "\n",
        "In the **Grant this service account access to project** section, click the Role drop-down list. Type \"Vertex\" into the filter box, and select **Vertex Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
        "\n",
        "Click Create. A JSON file that contains your key downloads to your local environment.\n",
        "\n",
        "Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gcp_authenticate"
      },
      "outputs": [],
      "source": [
        "# If you are running this notebook in Colab, run this cell and follow the\n",
        "# instructions to authenticate your GCP account. This provides access to your\n",
        "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
        "# requests.\n",
        "\n",
        "# If on Google Cloud Notebook, then don't execute this code\n",
        "if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
        "    if \"google.colab\" in sys.modules:\n",
        "        from google.colab import auth as google_auth\n",
        "\n",
        "        google_auth.authenticate_user()\n",
        "\n",
        "    # If you are running this notebook locally, replace the string below with the\n",
        "    # path to your service account key and run this cell to authenticate your GCP\n",
        "    # account.\n",
        "    elif not os.getenv(\"IS_TESTING\"):\n",
        "        %env GOOGLE_APPLICATION_CREDENTIALS ''"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bucket:export_cloud"
      },
      "source": [
        "### Create a Cloud Storage bucket\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for exporting the trained model. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
        "\n",
        "Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bucket"
      },
      "outputs": [],
      "source": [
        "BUCKET_NAME = \"gs://[your-bucket-name]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_bucket"
      },
      "outputs": [],
      "source": [
        "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
        "    BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_bucket"
      },
      "source": [
        "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "create_bucket"
      },
      "outputs": [],
      "source": [
        "! gsutil mb -l $REGION $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "validate_bucket"
      },
      "source": [
        "Finally, validate access to your Cloud Storage bucket by examining its contents:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "validate_bucket"
      },
      "outputs": [],
      "source": [
        "! gsutil ls -al $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "import_aip:protobuf"
      },
      "source": [
        "#### Import Vertex client library\n",
        "\n",
        "Import the Vertex client library into our Python environment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "import_aip:protobuf"
      },
      "outputs": [],
      "source": [
        "import time\n",
        "\n",
        "from google.cloud.aiplatform import gapic as aip\n",
        "from google.protobuf import json_format\n",
        "from google.protobuf.json_format import MessageToJson, ParseDict\n",
        "from google.protobuf.struct_pb2 import Struct, Value"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aip_constants"
      },
      "source": [
        "#### Vertex constants\n",
        "\n",
        "Setup up the following constants for Vertex:\n",
        "\n",
        "- `API_ENDPOINT`: The Vertex API service endpoint for dataset, model, job, pipeline and endpoint services.\n",
        "- `PARENT`: The Vertex location root path for dataset, model, job, pipeline and endpoint resources."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "aip_constants"
      },
      "outputs": [],
      "source": [
        "# API service endpoint\n",
        "API_ENDPOINT = \"{}-aiplatform.googleapis.com\".format(REGION)\n",
        "\n",
        "# Vertex location root path for your dataset, model and endpoint resources\n",
        "PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "automl_constants"
      },
      "source": [
        "#### AutoML constants\n",
        "\n",
        "Set constants unique to AutoML datasets and training:\n",
        "\n",
        "- Dataset Schemas: Tells the `Dataset` resource service which type of dataset it is.\n",
        "- Data Labeling (Annotations) Schemas: Tells the `Dataset` resource service how the data is labeled (annotated).\n",
        "- Dataset Training Schemas: Tells the `Pipeline` resource service the task (e.g., classification) to train the model for."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "automl_constants:lcn"
      },
      "outputs": [],
      "source": [
        "# Tabular Dataset type\n",
        "DATA_SCHEMA = \"gs://google-cloud-aiplatform/schema/dataset/metadata/tables_1.0.0.yaml\"\n",
        "# Tabular Labeling type\n",
        "LABEL_SCHEMA = (\n",
        "    \"gs://google-cloud-aiplatform/schema/dataset/ioformat/table_io_format_1.0.0.yaml\"\n",
        ")\n",
        "# Tabular Training task\n",
        "TRAINING_SCHEMA = \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_tables_1.0.0.yaml\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_docker"
      },
      "source": [
        "### Install Docker (Colab or Local)\n",
        "\n",
        "If you are using Google Cloud Notebook, Docker is already installed. Skip these steps.\n",
        "\n",
        "By default, Docker is not installed on Colab. If you're running colab, then you need to do the following to install Docker."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "install_docker"
      },
      "outputs": [],
      "source": [
        "if \"google.colab\" in sys.modules:\n",
        "    ! sudo apt update\n",
        "    ! sudo apt install apt-transport-https ca-certificates curl software-properties-common\n",
        "    ! curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n",
        "    ! sudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu bionic stable\"\n",
        "    ! sudo apt update\n",
        "    ! sudo apt install docker-ce"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "start_docker_service"
      },
      "source": [
        "#### Start Docker service\n",
        "\n",
        "Start the `docker` service."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "start_docker_service"
      },
      "outputs": [],
      "source": [
        "if \"google.colab\" in sys.modules:\n",
        "    ! sudo service docker start"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tutorial_start:automl"
      },
      "source": [
        "# Tutorial\n",
        "\n",
        "Now you are ready to start creating your own AutoML tabular classification model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "clients:automl,export_cloud"
      },
      "source": [
        "## Set up clients\n",
        "\n",
        "The Vertex client library works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex server.\n",
        "\n",
        "You will use different clients in this tutorial for different steps in the workflow. So set them all up upfront.\n",
        "\n",
        "- Dataset Service for `Dataset` resources.\n",
        "- Model Service for `Model` resources.\n",
        "- Pipeline Service for training."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "clients:automl,export_cloud"
      },
      "outputs": [],
      "source": [
        "# client options same for all services\n",
        "client_options = {\"api_endpoint\": API_ENDPOINT}\n",
        "\n",
        "\n",
        "def create_dataset_client():\n",
        "    client = aip.DatasetServiceClient(client_options=client_options)\n",
        "    return client\n",
        "\n",
        "\n",
        "def create_model_client():\n",
        "    client = aip.ModelServiceClient(client_options=client_options)\n",
        "    return client\n",
        "\n",
        "\n",
        "def create_pipeline_client():\n",
        "    client = aip.PipelineServiceClient(client_options=client_options)\n",
        "    return client\n",
        "\n",
        "\n",
        "clients = {}\n",
        "clients[\"dataset\"] = create_dataset_client()\n",
        "clients[\"model\"] = create_model_client()\n",
        "clients[\"pipeline\"] = create_pipeline_client()\n",
        "\n",
        "for client in clients.items():\n",
        "    print(client)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dataset:tabular"
      },
      "source": [
        "## Dataset\n",
        "\n",
        "Now that your clients are ready, your first step is to create a `Dataset` resource instance. This step differs from Vision, Video and Language. For those products, after the `Dataset` resource is created, one then separately imports the data, using the `import_data` method.\n",
        "\n",
        "For tabular, importing of the data is deferred until the training pipeline starts training the model. What do we do different? Well, first you won't be calling the `import_data` method. Instead, when you create the dataset instance you specify the Cloud Storage location of the CSV file or BigQuery location of the data table, which contains your tabular data as part of the `Dataset` resource's metadata.\n",
        "\n",
        "#### Cloud Storage\n",
        "\n",
        "`metadata = {\"input_config\": {\"gcs_source\": {\"uri\": [gcs_uri]}}}`\n",
        "\n",
        "The format for a Cloud Storage path is:\n",
        "\n",
        "    gs://[bucket_name]/[folder(s)/[file]\n",
        "\n",
        "#### BigQuery\n",
        "\n",
        "`metadata = {\"input_config\": {\"bigquery_source\": {\"uri\": [gcs_uri]}}}`\n",
        "\n",
        "The format for a BigQuery path is:\n",
        "\n",
        "    bq://[collection].[dataset].[table]\n",
        "\n",
        "Note that the `uri` field is a list, whereby you can input multiple CSV files or BigQuery tables when your data is split across files."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "data_preparation:tabular,u_dataset"
      },
      "source": [
        "### Data preparation\n",
        "\n",
        "The Vertex `Dataset` resource for tabular has a couple of requirements for your tabular data.\n",
        "\n",
        "- Must be in a CSV file or a BigQuery query."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "data_import_format:lcn,u_dataset,csv"
      },
      "source": [
        "#### CSV\n",
        "\n",
        "For tabular classification, the CSV file has a few requirements:\n",
        "\n",
        "- The first row must be the heading -- note how this is different from Vision, Video and Language where the requirement is no heading.\n",
        "- All but one column are features.\n",
        "- One column is the label, which you will specify when you subsequently create the training pipeline."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "import_file:u_dataset,csv"
      },
      "source": [
        "#### Location of Cloud Storage training data.\n",
        "\n",
        "Now set the variable `IMPORT_FILE` to the location of the CSV index file in Cloud Storage."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "import_file:iris,csv,lcn"
      },
      "outputs": [],
      "source": [
        "IMPORT_FILE = \"gs://cloud-samples-data/tables/iris_1000.csv\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "quick_peek:tabular"
      },
      "source": [
        "#### Quick peek at your data\n",
        "\n",
        "You will use a version of the Iris dataset that is stored in a public Cloud Storage bucket, using a CSV index file.\n",
        "\n",
        "Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file  (`wc -l`) and then peek at the first few rows.\n",
        "\n",
        "You also need for training to know the heading name of the label column, which is save as `label_column`. For this dataset, it is the last column in the CSV file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "quick_peek:tabular"
      },
      "outputs": [],
      "source": [
        "count = ! gsutil cat $IMPORT_FILE | wc -l\n",
        "print(\"Number of Examples\", int(count[0]))\n",
        "\n",
        "print(\"First 10 rows\")\n",
        "! gsutil cat $IMPORT_FILE | head\n",
        "\n",
        "heading = ! gsutil cat $IMPORT_FILE | head -n1\n",
        "label_column = str(heading).split(\",\")[-1].split(\"'\")[0]\n",
        "print(\"Label Column Name\", label_column)\n",
        "if label_column is None:\n",
        "    raise Exception(\"label column missing\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_aip_dataset:tabular"
      },
      "source": [
        "## Dataset\n",
        "\n",
        "Now that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it.\n",
        "\n",
        "### Create `Dataset` resource instance\n",
        "\n",
        "Use the helper function `create_dataset` to create the instance of a `Dataset` resource. This function does the following:\n",
        "\n",
        "1. Uses the dataset client service.\n",
        "2. Creates an Vertex `Dataset` resource (`aip.Dataset`), with the following parameters:\n",
        " - `display_name`: The human-readable name you choose to give it.\n",
        " - `metadata_schema_uri`: The schema for the dataset type.\n",
        " - `metadata`: The Cloud Storage or BigQuery location of the tabular data.\n",
        "3. Calls the client dataset service method `create_dataset`, with the following parameters:\n",
        " - `parent`: The Vertex location root path for your `Database`, `Model` and `Endpoint` resources.\n",
        " - `dataset`: The Vertex dataset object instance you created.\n",
        "4. The method returns an `operation` object.\n",
        "\n",
        "An `operation` object is how Vertex handles asynchronous calls for long running operations. While this step usually goes fast, when you first use it in your project, there is a longer delay due to provisioning.\n",
        "\n",
        "You can use the `operation` object to get status on the operation (e.g., create `Dataset` resource) or to cancel the operation, by invoking an operation method:\n",
        "\n",
        "| Method      | Description |\n",
        "| ----------- | ----------- |\n",
        "| result()    | Waits for the operation to complete and returns a result object in JSON format.      |\n",
        "| running()   | Returns True/False on whether the operation is still running.        |\n",
        "| done()      | Returns True/False on whether the operation is completed. |\n",
        "| canceled()  | Returns True/False on whether the operation was canceled. |\n",
        "| cancel()    | Cancels the operation (this may take up to 30 seconds). |"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "create_aip_dataset:tabular"
      },
      "outputs": [],
      "source": [
        "TIMEOUT = 90\n",
        "\n",
        "\n",
        "def create_dataset(name, schema, src_uri=None, labels=None, timeout=TIMEOUT):\n",
        "    start_time = time.time()\n",
        "    try:\n",
        "        if src_uri.startswith(\"gs://\"):\n",
        "            metadata = {\"input_config\": {\"gcs_source\": {\"uri\": [src_uri]}}}\n",
        "        elif src_uri.startswith(\"bq://\"):\n",
        "            metadata = {\"input_config\": {\"bigquery_source\": {\"uri\": [src_uri]}}}\n",
        "        dataset = aip.Dataset(\n",
        "            display_name=name,\n",
        "            metadata_schema_uri=schema,\n",
        "            labels=labels,\n",
        "            metadata=json_format.ParseDict(metadata, Value()),\n",
        "        )\n",
        "\n",
        "        operation = clients[\"dataset\"].create_dataset(parent=PARENT, dataset=dataset)\n",
        "        print(\"Long running operation:\", operation.operation.name)\n",
        "        result = operation.result(timeout=TIMEOUT)\n",
        "        print(\"time:\", time.time() - start_time)\n",
        "        print(\"response\")\n",
        "        print(\" name:\", result.name)\n",
        "        print(\" display_name:\", result.display_name)\n",
        "        print(\" metadata_schema_uri:\", result.metadata_schema_uri)\n",
        "        print(\" metadata:\", dict(result.metadata))\n",
        "        print(\" create_time:\", result.create_time)\n",
        "        print(\" update_time:\", result.update_time)\n",
        "        print(\" etag:\", result.etag)\n",
        "        print(\" labels:\", dict(result.labels))\n",
        "        return result\n",
        "    except Exception as e:\n",
        "        print(\"exception:\", e)\n",
        "        return None\n",
        "\n",
        "\n",
        "result = create_dataset(\"iris-\" + TIMESTAMP, DATA_SCHEMA, src_uri=IMPORT_FILE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dataset_id:result"
      },
      "source": [
        "Now save the unique dataset identifier for the `Dataset` resource instance you created."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "dataset_id:result"
      },
      "outputs": [],
      "source": [
        "# The full unique ID for the dataset\n",
        "dataset_id = result.name\n",
        "# The short numeric ID for the dataset\n",
        "dataset_short_id = dataset_id.split(\"/\")[-1]\n",
        "\n",
        "print(dataset_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_automl_model"
      },
      "source": [
        "## Train the model\n",
        "\n",
        "Now train an AutoML tabular classification model using your Vertex `Dataset` resource. To train the model, do the following steps:\n",
        "\n",
        "1. Create an Vertex training pipeline for the `Dataset` resource.\n",
        "2. Execute the pipeline to start the training."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_pipeline:automl"
      },
      "source": [
        "### Create a training pipeline\n",
        "\n",
        "You may ask, what do we use a pipeline for? You typically use pipelines when the job (such as training) has multiple steps, generally in sequential order: do step A, do step B, etc. By putting the steps into a pipeline, we gain the benefits of:\n",
        "\n",
        "1. Being reusable for subsequent training jobs.\n",
        "2. Can be containerized and ran as a batch job.\n",
        "3. Can be distributed.\n",
        "4. All the steps are associated with the same pipeline job for tracking progress.\n",
        "\n",
        "Use this helper function `create_pipeline`, which takes the following parameters:\n",
        "\n",
        "- `pipeline_name`: A human readable name for the pipeline job.\n",
        "- `model_name`: A human readable name for the model.\n",
        "- `dataset`: The Vertex fully qualified dataset identifier.\n",
        "- `schema`: The dataset labeling (annotation) training schema.\n",
        "- `task`: A dictionary describing the requirements for the training job.\n",
        "\n",
        "The helper function calls the `Pipeline` client service'smethod `create_pipeline`, which takes the following parameters:\n",
        "\n",
        "- `parent`: The Vertex location root path for your `Dataset`, `Model` and `Endpoint` resources.\n",
        "- `training_pipeline`: the full specification for the pipeline training job.\n",
        "\n",
        "Let's look now deeper into the *minimal* requirements for constructing a `training_pipeline` specification:\n",
        "\n",
        "- `display_name`: A human readable name for the pipeline job.\n",
        "- `training_task_definition`: The dataset labeling (annotation) training schema.\n",
        "- `training_task_inputs`: A dictionary describing the requirements for the training job.\n",
        "- `model_to_upload`: A human readable name for the model.\n",
        "- `input_data_config`: The dataset specification.\n",
        " - `dataset_id`: The Vertex dataset identifier only (non-fully qualified) -- this is the last part of the fully-qualified identifier.\n",
        " - `fraction_split`: If specified, the percentages of the dataset to use for training, test and validation. Otherwise, the percentages are automatically selected by AutoML."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "create_pipeline:automl"
      },
      "outputs": [],
      "source": [
        "def create_pipeline(pipeline_name, model_name, dataset, schema, task):\n",
        "\n",
        "    dataset_id = dataset.split(\"/\")[-1]\n",
        "\n",
        "    input_config = {\n",
        "        \"dataset_id\": dataset_id,\n",
        "        \"fraction_split\": {\n",
        "            \"training_fraction\": 0.8,\n",
        "            \"validation_fraction\": 0.1,\n",
        "            \"test_fraction\": 0.1,\n",
        "        },\n",
        "    }\n",
        "\n",
        "    training_pipeline = {\n",
        "        \"display_name\": pipeline_name,\n",
        "        \"training_task_definition\": schema,\n",
        "        \"training_task_inputs\": task,\n",
        "        \"input_data_config\": input_config,\n",
        "        \"model_to_upload\": {\"display_name\": model_name},\n",
        "    }\n",
        "\n",
        "    try:\n",
        "        pipeline = clients[\"pipeline\"].create_training_pipeline(\n",
        "            parent=PARENT, training_pipeline=training_pipeline\n",
        "        )\n",
        "        print(pipeline)\n",
        "    except Exception as e:\n",
        "        print(\"exception:\", e)\n",
        "        return None\n",
        "    return pipeline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "task_requirements:automl,tabular"
      },
      "source": [
        "### Construct the task requirements\n",
        "\n",
        "Next, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the `task` field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the `json_format.ParseDict` method for the conversion.\n",
        "\n",
        "The minimal fields you need to specify are:\n",
        "\n",
        "- `prediction_type`: Whether we are doing \"classification\" or \"regression\".\n",
        "- `target_column`: The CSV heading column name for the column we want to predict (i.e., the label).\n",
        "- `train_budget_milli_node_hours`: The maximum time to budget (billed) for training the model, where 1000 = 1 hour.\n",
        "- `disable_early_stopping`: Whether True/False to let AutoML use its judgement to stop training early or train for the entire budget.\n",
        "- `transformations`: Specifies the feature engineering for each feature column.\n",
        "\n",
        "For `transformations`, the list must have an entry for each column. The outer key field indicates the type of feature engineering for the corresponding column. In this tutorial, you set it to `\"auto\"` to tell AutoML to automatically determine it.\n",
        "\n",
        "Finally, create the pipeline by calling the helper function `create_pipeline`, which returns an instance of a training pipeline object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "task_transformations:automl,tabular,iris"
      },
      "outputs": [],
      "source": [
        "TRANSFORMATIONS = [\n",
        "    {\"auto\": {\"column_name\": \"sepal_width\"}},\n",
        "    {\"auto\": {\"column_name\": \"sepal_length\"}},\n",
        "    {\"auto\": {\"column_name\": \"petal_length\"}},\n",
        "    {\"auto\": {\"column_name\": \"petal_width\"}},\n",
        "]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "task_requirements:automl,tabular,transformations"
      },
      "outputs": [],
      "source": [
        "PIPE_NAME = \"iris_pipe-\" + TIMESTAMP\n",
        "MODEL_NAME = \"iris_model-\" + TIMESTAMP\n",
        "\n",
        "task = Value(\n",
        "    struct_value=Struct(\n",
        "        fields={\n",
        "            \"target_column\": Value(string_value=label_column),\n",
        "            \"prediction_type\": Value(string_value=\"classification\"),\n",
        "            \"train_budget_milli_node_hours\": Value(number_value=1000),\n",
        "            \"disable_early_stopping\": Value(bool_value=False),\n",
        "            \"transformations\": json_format.ParseDict(TRANSFORMATIONS, Value()),\n",
        "        }\n",
        "    )\n",
        ")\n",
        "\n",
        "response = create_pipeline(PIPE_NAME, MODEL_NAME, dataset_id, TRAINING_SCHEMA, task)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pipeline_id:response"
      },
      "source": [
        "Now save the unique identifier of the training pipeline you created."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "pipeline_id:response"
      },
      "outputs": [],
      "source": [
        "# The full unique ID for the pipeline\n",
        "pipeline_id = response.name\n",
        "# The short numeric ID for the pipeline\n",
        "pipeline_short_id = pipeline_id.split(\"/\")[-1]\n",
        "\n",
        "print(pipeline_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "get_training_pipeline"
      },
      "source": [
        "### Get information on a training pipeline\n",
        "\n",
        "Now get pipeline information for just this training pipeline instance. The helper function  gets the job information for just this job by calling the the job client service's `get_training_pipeline` method, with the following parameter:\n",
        "\n",
        "- `name`: The Vertex fully qualified pipeline identifier.\n",
        "\n",
        "When the model is done training, the pipeline state will be `PIPELINE_STATE_SUCCEEDED`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "get_training_pipeline"
      },
      "outputs": [],
      "source": [
        "def get_training_pipeline(name, silent=False):\n",
        "    response = clients[\"pipeline\"].get_training_pipeline(name=name)\n",
        "    if silent:\n",
        "        return response\n",
        "\n",
        "    print(\"pipeline\")\n",
        "    print(\" name:\", response.name)\n",
        "    print(\" display_name:\", response.display_name)\n",
        "    print(\" state:\", response.state)\n",
        "    print(\" training_task_definition:\", response.training_task_definition)\n",
        "    print(\" training_task_inputs:\", dict(response.training_task_inputs))\n",
        "    print(\" create_time:\", response.create_time)\n",
        "    print(\" start_time:\", response.start_time)\n",
        "    print(\" end_time:\", response.end_time)\n",
        "    print(\" update_time:\", response.update_time)\n",
        "    print(\" labels:\", dict(response.labels))\n",
        "    return response\n",
        "\n",
        "\n",
        "response = get_training_pipeline(pipeline_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wait_training_complete"
      },
      "source": [
        "# Deployment\n",
        "\n",
        "Training the above model may take upwards of 30 minutes time.\n",
        "\n",
        "Once your model is done training, you can calculate the actual time it took to train the model by subtracting `end_time` from `start_time`. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline service assigned to it. You can get this from the returned pipeline instance as the field `model_to_deploy.name`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wait_training_complete"
      },
      "outputs": [],
      "source": [
        "while True:\n",
        "    response = get_training_pipeline(pipeline_id, True)\n",
        "    if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:\n",
        "        print(\"Training job has not completed:\", response.state)\n",
        "        model_to_deploy_id = None\n",
        "        if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:\n",
        "            raise Exception(\"Training Job Failed\")\n",
        "    else:\n",
        "        model_to_deploy = response.model_to_upload\n",
        "        model_to_deploy_id = model_to_deploy.name\n",
        "        print(\"Training Time:\", response.end_time - response.start_time)\n",
        "        break\n",
        "    time.sleep(60)\n",
        "\n",
        "print(\"model to deploy:\", model_to_deploy_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "model_information"
      },
      "source": [
        "## Model information\n",
        "\n",
        "Now that your model is trained, you can get some information on your model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "evaluate_the_model:automl"
      },
      "source": [
        "## Evaluate the Model resource\n",
        "\n",
        "Now find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to evaluate the model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "list_model_evaluations:automl,lcn"
      },
      "source": [
        "### List evaluations for all slices\n",
        "\n",
        "Use this helper function `list_model_evaluations`, which takes the following parameter:\n",
        "\n",
        "- `name`: The Vertex fully qualified model identifier for the `Model` resource.\n",
        "\n",
        "This helper function uses the model client service's `list_model_evaluations` method, which takes the same parameter. The response object from the call is a list, where each element is an evaluation metric.\n",
        "\n",
        "For each evaluation (you probably only have one) we then print all the key names for each metric in the evaluation, and for a small set (`logLoss` and `auPrc`) you will print the result."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "list_model_evaluations:automl,lcn"
      },
      "outputs": [],
      "source": [
        "def list_model_evaluations(name):\n",
        "    response = clients[\"model\"].list_model_evaluations(parent=name)\n",
        "    for evaluation in response:\n",
        "        print(\"model_evaluation\")\n",
        "        print(\" name:\", evaluation.name)\n",
        "        print(\" metrics_schema_uri:\", evaluation.metrics_schema_uri)\n",
        "        metrics = json_format.MessageToDict(evaluation._pb.metrics)\n",
        "        for metric in metrics.keys():\n",
        "            print(metric)\n",
        "        print(\"logloss\", metrics[\"logLoss\"])\n",
        "        print(\"auPrc\", metrics[\"auPrc\"])\n",
        "\n",
        "    return evaluation.name\n",
        "\n",
        "\n",
        "last_evaluation = list_model_evaluations(model_to_deploy_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "export_model:export_cloud"
      },
      "source": [
        "## Export as cloud model\n",
        "\n",
        "You can export an AutoML tabular classification model as a TensorFlow SavedFormat model which you can then custom deploy to Google Cloud or download locally. Use this helper function `export_model` to export the model to Google Cloud, which takes the following parameters:\n",
        "\n",
        "- `name`: The Vertex fully qualified identifier for the `Model` resource.\n",
        "- `gcs_dest`: The Cloud Storage location to store the SavedFormat model artifacts to.\n",
        "\n",
        "This function calls the `Model` client service's method `export_model`, with the following parameters:\n",
        "\n",
        "- `name`: The Vertex fully qualified identifier for the `Model` resource.\n",
        "- `output_config`: The destination information for the exported model.\n",
        "  - `artifact_destination.output_uri_prefix`: The Cloud Storage location to store the SavedFormat model artifacts to.\n",
        "  - `export_format_id`: The format to save the model format as. For AutoML tabular classification there is just one option:\n",
        "   - `tf-saved-model`: TensorFlow SavedFormat\n",
        "\n",
        "The method returns a long running operation `response`. We will wait sychronously for the operation to complete by calling the `response.result()`, which will block until the model is exported."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "export_model:export_cloud"
      },
      "outputs": [],
      "source": [
        "MODEL_DIR = BUCKET_NAME + \"/\" + \"iris\"\n",
        "\n",
        "\n",
        "def export_model(name, format, gcs_dest):\n",
        "    output_config = {\n",
        "        \"artifact_destination\": {\"output_uri_prefix\": gcs_dest},\n",
        "        \"export_format_id\": format,\n",
        "    }\n",
        "    response = clients[\"model\"].export_model(name=name, output_config=output_config)\n",
        "    print(\"Long running operation:\", response.operation.name)\n",
        "    result = response.result(timeout=1800)\n",
        "    metadata = response.operation.metadata\n",
        "    artifact_uri = str(metadata.value).split(\"\\\\\")[-1][4:-1]\n",
        "    print(\"Artifact Uri\", artifact_uri)\n",
        "    return artifact_uri\n",
        "\n",
        "\n",
        "model_package = export_model(model_to_deploy_id, \"tf-saved-model\", MODEL_DIR)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "export_model_layout:export_cloud"
      },
      "source": [
        "### Running the exported model package\n",
        "\n",
        "Your model is now stored in a TensorFlow SavedModel format, along with a model server binary in a Cloud Storage bucket. Load the model locally from the Cloud Storage bucket, and then you can do some things like deploy the model and serving binary locally using Docker with a prebuilt Google Cloud container designed for running the model server.\n",
        "\n",
        "#### Model package layout\n",
        "\n",
        "Let's start with looking at what is in the exported package. The exported model package will be stored in your Cloud Storage bucket as:\n",
        "\n",
        "    <your-gcs-bucket>/<model_name>/model-<model id>/tf-saved-model/<timedstamp>\n",
        "\n",
        "Next, take a look at the contents of the model package."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "export_model_layout:export_cloud"
      },
      "outputs": [],
      "source": [
        "print(\"Model Package:\", model_package)\n",
        "print(\"Contents:\")\n",
        "! gsutil ls $model_package\n",
        "\n",
        "print(\"\\nTF Saved Model\")\n",
        "path = model_package + \"/predict\"\n",
        "files = ! gsutil ls $path\n",
        "saved_dir = files[1]\n",
        "print(saved_dir)\n",
        "! gsutil ls $saved_dir"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "download_exported_model:export_cloud"
      },
      "source": [
        "#### Downloading the export model package.\n",
        "\n",
        "Your first step is to download the exported model package locally."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "download_exported_model:export_cloud"
      },
      "outputs": [],
      "source": [
        "! gsutil cp -r $model_package ."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rename_exported_model:export_cloud"
      },
      "source": [
        "#### Rename the model package directory name\n",
        "\n",
        "In this tutorial, you will launch the model package using Docker. The timestamp in the last component of the path name for the package contains a ':', which is invalid for Docker. You will need to rename. In the next step, we rename the last component to `tbl_exported`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "rename_exported_model:export_cloud"
      },
      "outputs": [],
      "source": [
        "subdir = model_package.split(\"/\")[-1]\n",
        "print(subdir)\n",
        "! mv $subdir tbl_exported"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "run_exported_model:local"
      },
      "source": [
        "### Run the exported model package\n",
        "\n",
        "This model package has dependencies on a prebuilt Google Cloud container that is specific for serving an export AutoML tabular classification model:\n",
        "\n",
        "    \"gcr.io/cloud-aiplatform/automl_tables/prediction_server\"\n",
        "\n",
        "This container is currently not supported by Vertex endpoint. You can though launch the model server with the container, either locally or on another compute instance you manage.\n",
        "\n",
        "In this tutorial, you will launch it with `docker`. The Docker container will run in the background of this notebook, using detached mode by specifying the `-d` option to `docker`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "run_exported_model:local"
      },
      "outputs": [],
      "source": [
        "MODEL_SERVER = \"gcr.io/cloud-aiplatform/automl_tables/prediction_server\"\n",
        "PORT = 8081\n",
        "\n",
        "docker_id = ! docker run -d -v `pwd`/tbl_exported:/models/default -p 8081:8080 -it $MODEL_SERVER"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "check_health_status:local"
      },
      "source": [
        "#### Check health status\n",
        "\n",
        "We need to let a bit of time to go by for the model to be loaded. Let's pause 10 seconds and then do a health check. If the health check comes back empty, it is ready to go."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "check_health_status:local"
      },
      "outputs": [],
      "source": [
        "import time\n",
        "\n",
        "time.sleep(10)\n",
        "! curl -X GET http://localhost:8081/health"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "docker_verified_loaded:local"
      },
      "source": [
        "#### Verify loading of docker image\n",
        "\n",
        "You can also verify the loading of the Docker image with `docker container ls`. We will add `--latest` to get information on the latest (this image) that was loaded."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "docker_verified_loaded:local"
      },
      "outputs": [],
      "source": [
        "! docker container ls --latest"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "make_prediction:automl,export_cloud,tabular"
      },
      "source": [
        "## Make a prediction request\n",
        "\n",
        "Now do a prediction with your exported model.\n",
        "\n",
        "### Prediction request format\n",
        "\n",
        "The format for the prediction request is a JSON object of the form:\n",
        "\n",
        "    { \"instances\": [ { \"column_name_1\": value, \"column_name_2\": value, … } , … ] }\n",
        "\n",
        "Place your prediction request in a text file, such as:\n",
        "\n",
        "    test.json"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "make_instances_file:tabular,iris"
      },
      "outputs": [],
      "source": [
        "INSTANCES = {\n",
        "    \"instances\": [\n",
        "        {\n",
        "            \"petal_length\": \"1.4\",\n",
        "            \"petal_width\": \"1.3\",\n",
        "            \"sepal_length\": \"5.1\",\n",
        "            \"sepal_width\": \"2.8\",\n",
        "        }\n",
        "    ]\n",
        "}\n",
        "\n",
        "import json\n",
        "\n",
        "with open(\"test.json\", \"w\") as f:\n",
        "    data = json.dumps(INSTANCES)\n",
        "    f.write(data)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "predict_item:local,curl"
      },
      "source": [
        "#### Send the prediction request\n",
        "\n",
        "You can the send the prediction request using CURL:\n",
        "\n",
        "    curl -X POST --data @test.json http://localhost:8081/predict"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "predict_item:local,curl"
      },
      "outputs": [],
      "source": [
        "! curl -X POST --data @/home/jupyter/test.json http://localhost:8081/predict"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "docker_shutdown:local"
      },
      "source": [
        "#### Shutdown the Docker container"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "docker_shutdown:local"
      },
      "outputs": [],
      "source": [
        "print(docker_id)\n",
        "! docker kill $docker_id"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cleanup"
      },
      "source": [
        "# Cleaning up\n",
        "\n",
        "To clean up all GCP resources used in this project, you can [delete the GCP\n",
        "project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
        "\n",
        "Otherwise, you can delete the individual resources you created in this tutorial:\n",
        "\n",
        "- Dataset\n",
        "- Pipeline\n",
        "- Model\n",
        "- Endpoint\n",
        "- Batch Job\n",
        "- Custom Job\n",
        "- Hyperparameter Tuning Job\n",
        "- Cloud Storage Bucket"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cleanup"
      },
      "outputs": [],
      "source": [
        "delete_dataset = True\n",
        "delete_pipeline = True\n",
        "delete_model = True\n",
        "delete_endpoint = True\n",
        "delete_batchjob = True\n",
        "delete_customjob = True\n",
        "delete_hptjob = True\n",
        "delete_bucket = True\n",
        "\n",
        "# Delete the dataset using the Vertex fully qualified identifier for the dataset\n",
        "try:\n",
        "    if delete_dataset and \"dataset_id\" in globals():\n",
        "        clients[\"dataset\"].delete_dataset(name=dataset_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the training pipeline using the Vertex fully qualified identifier for the pipeline\n",
        "try:\n",
        "    if delete_pipeline and \"pipeline_id\" in globals():\n",
        "        clients[\"pipeline\"].delete_training_pipeline(name=pipeline_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the model using the Vertex fully qualified identifier for the model\n",
        "try:\n",
        "    if delete_model and \"model_to_deploy_id\" in globals():\n",
        "        clients[\"model\"].delete_model(name=model_to_deploy_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the endpoint using the Vertex fully qualified identifier for the endpoint\n",
        "try:\n",
        "    if delete_endpoint and \"endpoint_id\" in globals():\n",
        "        clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the batch job using the Vertex fully qualified identifier for the batch job\n",
        "try:\n",
        "    if delete_batchjob and \"batch_job_id\" in globals():\n",
        "        clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the custom job using the Vertex fully qualified identifier for the custom job\n",
        "try:\n",
        "    if delete_customjob and \"job_id\" in globals():\n",
        "        clients[\"job\"].delete_custom_job(name=job_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "# Delete the hyperparameter tuning job using the Vertex fully qualified identifier for the hyperparameter tuning job\n",
        "try:\n",
        "    if delete_hptjob and \"hpt_job_id\" in globals():\n",
        "        clients[\"job\"].delete_hyperparameter_tuning_job(name=hpt_job_id)\n",
        "except Exception as e:\n",
        "    print(e)\n",
        "\n",
        "if delete_bucket and \"BUCKET_NAME\" in globals():\n",
        "    ! gsutil rm -r $BUCKET_NAME"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "showcase_automl_tabular_classification_export_cloud.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
